package org.jeecg.modules.qy_wechat.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import org.apache.commons.codec.binary.Base64;
import org.jeecg.common.util.UUIDGenerator;
import org.jeecg.modules.qy_wechat.entity.QyWechat;
import org.jeecg.modules.qy_wechat.mapper.QyWechatMapper;
import org.jeecg.modules.qy_wechat.service.IQyWechatService;
import org.jeecg.modules.qy_wechat.utils.HttpUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
    /**
     * 企业微信应用聊天服务实现类
     */
    @Service
    @Slf4j
    public class QyWechatServiceImpl extends ServiceImpl<QyWechatMapper, QyWechat> implements IQyWechatService {


        @Value("${qywechat.nurse.agentId:}")
        private String agentId;

        @Value("${qywechat.nurse.corpId:}")
        private String corpid;

        @Value("${qywechat.nurse.secret:}")
        private String secret;

        @Value("${qywechat.nurse.corpIdah:}")
        private String corpidah;

        @Value("${qywechat.nurse.secretah:}")
        private String secretah;

        @Autowired
        private QyWechatMapper qyWechatMapper;


        // 缓存access_token，避免频繁请求
        private static String accessToken;
        private  static long tokenExpireTime;

        @Override
        public String createAppChat(QyWechat appChat,String org) throws Exception {
            // 获取访问令牌
            String accessToken = getAccessToken(org);

            String chat_id =createGroup(accessToken, appChat.getOwner(), appChat.getName(),
                    appChat.getUserlist().toArray(new String[appChat.getUserlist().size()]), null);
             System.out.println("11111111111111222chat_id"+chat_id);
            String config_id=addGroupChatJoinWay("LiHang",chat_id);
            System.out.println("11111111111111222config_id"+config_id);
           return  getGroupChatJoinWay(config_id);

        }


        @Override
        public String getAccessToken(String org) {
            String corpid1=corpid; //默认华声
            String secret1=secret;
            // 检查令牌是否过期
            if (accessToken != null && System.currentTimeMillis() < tokenExpireTime) {
                return accessToken;
            }
            //安好
            if(org!=null && org.length()>=6 &&"A01A03".equals(org.substring(0,6))){
                corpid1=corpidah;
                secret1=secretah;
            }
            // 重新获取令牌
            try {
                String url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken" +
                        "?corpid=" + corpid1 +
                        "&corpsecret=" + secret1;

                String response = HttpUtils.sendGet(url);
                JSONObject jsonResponse = JSONObject.parseObject(response);
                Integer errcode = jsonResponse.getInteger("errcode");

                if (errcode != null && errcode != 0) {
                    log.error("获取企业微信access_token失败，错误码：{}，错误信息：{}",
                            errcode, jsonResponse.getString("errmsg"));
                    throw new RuntimeException("获取企业微信access_token失败");
                }

                accessToken = jsonResponse.getString("access_token");
                int expiresIn = jsonResponse.getIntValue("expires_in");
                // 提前5分钟过期，避免临界点问题
                tokenExpireTime = System.currentTimeMillis() + (expiresIn - 300) * 1000;

                return accessToken;
            } catch (Exception e) {
                log.error("获取企业微信access_token异常", e);
                throw new RuntimeException("获取企业微信access_token异常", e);
            }
        }



        /**
         * 下载图片并转换为Base64字符串
         */
        private String downloadImageToBase64(String imageUrl) throws Exception {
            URL url = new URL(imageUrl);
            URLConnection connection = url.openConnection();
            connection.setConnectTimeout(5000);
            connection.setReadTimeout(5000);

            try (InputStream in = connection.getInputStream();
                 ByteArrayOutputStream out = new ByteArrayOutputStream()) {

                byte[] buffer = new byte[1024];
                int len;
                while ((len = in.read(buffer)) != -1) {
                    out.write(buffer, 0, len);
                }
                // 转换为Base64并添加前缀
                return "data:image/png;base64," + Base64.encodeBase64String(out.toByteArray());
            }


        }



        /**
         * 调用add_join_way接口，配置客户群进群方式
         *
         * @return
         */
        public String addGroupChatJoinWay(String OWNER_USERID,String CHAT_ID_LIST) throws JsonProcessingException {
            OkHttpClient client = new OkHttpClient();
            ObjectMapper objectMapper = new ObjectMapper();
            MediaType JSON = MediaType.get("application/json; charset=utf-8");
            String ADD_JOIN_WAY_URL =
                    "https://qyapi.weixin.qq.com/cgi-bin/externalcontact/groupchat/add_join_way?access_token=";

            // 构建add_join_way请求参数（JSON格式）
            Map<String, Object> requestData = new HashMap<>();
            requestData.put("scene", 2); // 场景值：2=群活码（支持关联多个群，满员自动切换）
            requestData.put("owner", OWNER_USERID); // 群主userid（必须在关联群的成员中）
            requestData.put("chat_id_list", CHAT_ID_LIST); // 关联的外部群chat_id列表
            requestData.put("title", "产品咨询群"); // 进群方式标题（显示在二维码下方）
            requestData.put("introduction", "扫码加入产品咨询群，获取最新服务"); // 进群简介
            requestData.put("expire_time", System.currentTimeMillis() + 7 * 24 * 60 * 60 * 1000); // 有效期7天（毫秒级）
            requestData.put("is_temp", false); // 是否临时群：false=永久群

            // 转换参数为JSON字符串
            String jsonData = objectMapper.writeValueAsString(requestData);
            RequestBody body = RequestBody.create(jsonData, JSON);

            // 发送POST请求
            Request request = new Request.Builder().url(ADD_JOIN_WAY_URL).post(body).build();
            try (Response response = client.newCall(request).execute()) {
                if (!response.isSuccessful() || response.body() == null) {
                    System.err.println("add_join_way请求失败，响应码：" + response.code());
                    return null;
                }

                // 解析响应结果
                String responseStr = response.body().string();
                Map<String, Object> resultMap = objectMapper.readValue(responseStr, Map.class);
                Integer errCode = (Integer) resultMap.get("errcode");
                if (errCode == 0) {
                    return (String) resultMap.get("config_id"); // 成功返回config_id
                } else {
                    System.err.println("add_join_way接口返回错误：" + resultMap.get("errmsg") + "，错误码：" + errCode);
                    return null;
                }
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }


        public String getGroupChatJoinWay(String configId) throws JsonProcessingException {
             OkHttpClient client = new OkHttpClient();
             ObjectMapper objectMapper = new ObjectMapper();
             MediaType JSON = MediaType.get("application/json; charset=utf-8");
             String GET_JOIN_WAY_URL =
                    "https://qyapi.weixin.qq.com/cgi-bin/externalcontact/groupchat/get_join_way?access_token=";

            // 构建get_join_way请求参数（仅需config_id）
            Map<String, Object> requestData = new HashMap<>();
            requestData.put("config_id", configId);

            // 转换参数为JSON字符串
            String jsonData = objectMapper.writeValueAsString(requestData);
            RequestBody body = RequestBody.create(jsonData, JSON);

            // 发送POST请求
            Request request = new Request.Builder().url(GET_JOIN_WAY_URL).post(body).build();
            try (Response response = client.newCall(request).execute()) {
                if (!response.isSuccessful() || response.body() == null) {
                    System.err.println("get_join_way请求失败，响应码：" + response.code());
                    return "";
                }

                // 解析响应结果（含二维码URL）
                String responseStr = response.body().string();
                Map<String, Object> resultMap = objectMapper.readValue(responseStr, Map.class);
                Integer errCode = (Integer) resultMap.get("errcode");
                if (errCode == 0) {
                    System.out.println("获取进群方式详情成功：");
                    System.out.println("群活码URL：" + resultMap.get("qrcode_url")); // 关键：进群二维码URL
                    System.out.println("关联群聊列表：" + resultMap.get("chat_id_list"));
                    System.out.println("有效期（秒）：" + resultMap.get("expire_time"));
                    return (String) resultMap.get("qrcode_url");
                } else {
                    System.err.println("get_join_way接口返回错误：" + resultMap.get("errmsg") + "，错误码：" + errCode);
                }
            } catch (JsonMappingException e) {
                throw new RuntimeException(e);
            } catch (JsonProcessingException e) {
                throw new RuntimeException(e);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
            return GET_JOIN_WAY_URL;
        }

        public  String createGroup(String accessToken, String owner, String groupName,
                                         String[] userList, String[] externalUserList) {
             String BASE_URL = "https://qyapi.weixin.qq.com/cgi-bin/externalcontact/groupchat/create";
            // JSON媒体类型
             MediaType JSON = MediaType.get("application/json; charset=utf-8");
            // Jackson JSON处理器
             ObjectMapper objectMapper = new ObjectMapper();
            // 构建完整请求URL
            String url = BASE_URL + "?access_token=" + accessToken;

            // 构建请求参数
            Map<String, Object> requestParams = new HashMap<>();
            requestParams.put("owner", owner);                  // 群主userid（必填）
            requestParams.put("name", groupName);               // 群名称（必填）
            requestParams.put("user_list", userList);           // 企业成员列表（可选）
            requestParams.put("external_userid_list", externalUserList); // 外部联系人列表（可选）
            // 可选：添加群公告（最多500字符）
            // requestParams.put("notice", "欢迎加入本群，请勿发送广告！");

            try {
                // 转换参数为JSON字符串
                String jsonParams = objectMapper.writeValueAsString(requestParams);

                // 创建请求体
                RequestBody body = RequestBody.create(jsonParams, JSON);

                // 创建请求
                Request request = new Request.Builder()
                        .url(url)
                        .post(body)
                        .build();

                // 发送请求
                OkHttpClient client = new OkHttpClient();
                try (Response response = client.newCall(request).execute()) {
                    if (!response.isSuccessful() || response.body() == null) {
                        System.err.println("创建群聊请求失败，响应码：" + response.code());
                        return null;
                    }

                    // 解析响应结果
                    String responseBody = response.body().string();
                    Map<String, Object> resultMap = objectMapper.readValue(responseBody, Map.class);

                    // 处理响应码
                    int errCode = (Integer) resultMap.get("errcode");
                    if (errCode == 0) {
                        // 成功获取chat_id
                        return (String) resultMap.get("chat_id");
                    } else {
                        System.err.println("创建群聊失败：" + resultMap.get("errmsg") + "，错误码：" + errCode);
                        return null;
                    }
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            } catch (JsonProcessingException e) {
                System.err.println("请求参数JSON序列化失败：" + e.getMessage());
            } catch (IOException e) {
                System.err.println("HTTP请求异常：" + e.getMessage());
            }
            return null;
        }




}
